﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;
using com.lover.common.json;

namespace com.lover.astd.common.partner.impl
{
    public class _53wanLogin : LoginImplBase
    {
        public _53wanLogin() : base() { }
        public override bool alwaysNeedVerifyCode() { return true; }
        public override string getAlwaysCaptchaImageUrl() { return "http://www.53wan.com/getCerification.do?login=1&r=" + _rand.NextDouble(); }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            
            if (verify_code == null)
            {
                buildAlwaysVerifyResult(ref result, ref cookies);
                return result;
            }

            string loginurl = "http://www.53wan.com/login.do";
            string data = String.Format("userName={0}&password={1}&validCode={2}&flag=1&marks=0&RTN_CUSTOM=rtn_as", 
                _username, _md5_password_lower, verify_code);
            HttpResult resp = TransferMgr.doPostPure(loginurl, data, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            string retstr = resp.getContent();
            if (retstr.Contains("alert"))
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            goingToGameUrl();
            string redirecturl = "http://www.53wan.com/jumpServer.do";
            data = String.Format("gameId=23&serverId={0}", _acc.ServerId);
            resp = TransferMgr.doPostPure(redirecturl, data, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }
            retstr = resp.getContent();
            JsonTextParser parser = new JsonTextParser();
            JsonObjectCollection obj_token = (JsonObjectCollection)parser.Parse(retstr);
            IEnumerator<JsonObject> token_enumer = obj_token.GetEnumerator();
            string url = "";
            while (token_enumer.MoveNext())
            {
                JsonStringValue token_item = token_enumer.Current as JsonStringValue;
                if (token_item == null) continue;
                if (token_item.Name != "returnMsg") continue;
                url = token_item.Value;
            }
            if (url == "") { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }

            processStartGame(url, result, ref cookies);
            return result;
        }
    }
}
